<template>
  <view class="cart-container">
    <!-- 全屏初始化加载动画 -->
    <view class="initial-loading-overlay" v-if="initialLoading">
      <view class="initial-loading-content">
        <view class="initial-loading-spinner"></view>
        <text class="initial-loading-text">正在加载...</text>
      </view>
    </view>

    <!-- 购物车商品列表（带滚动） -->
    <scroll-view class="cart-list-scroll" scroll-y v-if="cartItems.length > 0">
      <view class="cart-list">
        <view v-for="item in cartItems" :key="item.id" class="cart-item">
          <!-- 商品选择框 -->
          <view class="item-checkbox" @click.stop="toggleItemSelect(item)">
            <view class="checkbox" :class="{ checked: item.selected }">
              <uni-icons v-if="item.selected" type="checkmarkempty" size="16" color="#fff"></uni-icons>
            </view>
          </view>

          <!-- 商品信息 -->
          <view class="item-content">
            <image
              :src="item.productImage || item.mainImageUrl || '/static/default-product.png'"
              mode="aspectFill"
              class="item-image"
              @click="goToProductDetail(item)"
            />
            <view class="item-info">
              <text class="item-name" @click="goToProductDetail(item)">{{ item.productName }}</text>
              <text class="item-spec" v-if="item.attrValue">{{ item.attrValue }}</text>
              <view class="item-footer">
                <text class="item-price">¥{{ item.sellingPrice / 100 }}</text>
                <view class="item-quantity">
                  <view class="quantity-btn" @click.stop="decreaseQuantity(item)">
                    <text class="quantity-icon">-</text>
                  </view>
                  <text class="quantity-num">{{ item.quantity }}</text>
                  <view class="quantity-btn" @click.stop="increaseQuantity(item)">
                    <text class="quantity-icon">+</text>
                  </view>
                </view>
              </view>
            </view>
          </view>

          <!-- 删除按钮 -->
          <view class="item-delete" @click.stop="deleteItem(item)">
            <uni-icons type="trash" size="20" color="#999"></uni-icons>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 空购物车状态 -->
    <view v-else-if="!initialLoading" class="empty-cart">
      <image src="/static/icons/empty.png" mode="aspectFit" class="empty-icon" />
      <text class="empty-text">购物车是空的</text>
      <!-- <button class="go-shopping-btn" @click="goToHome">去逛逛</button> -->
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar" v-if="cartItems.length > 0">
      <view class="select-all" @click="toggleSelectAll">
        <view class="checkbox" :class="{ checked: isAllSelected }">
          <uni-icons v-if="isAllSelected" type="checkmarkempty" size="16" color="#fff"></uni-icons>
        </view>
        <text class="select-all-text">全选</text>
      </view>
      <view class="total-section">
        <view class="total-info">
          <text class="total-label">合计：</text>
          <text class="total-price">¥{{ totalPrice }}</text>
        </view>
        <!-- <text class="total-tip">免运费</text> -->
      </view>
      <button class="checkout-btn" :disabled="selectedCount === 0" @click="checkout">
        立即下单({{ selectedCount }})
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { getUserInfo } from '@/utils/auth';
import request from '@/utils/request';

// ==================== 数据类型定义 ====================
interface Address {
  id: number;
  receiverName: string;
  receiverPhone: string;
  province: string;
  city: string;
  district: string;
  address: string;
  fullAddress: string;
  isDefault?: boolean;
}

interface CartItem {
  id: string | number;
  productId: string | number;
  productName: string;
  productImage?: string;
  mainImageUrl?: string;
  attrValue?: string;
  sellingPrice: number;
  quantity: number;
  selected: boolean;
  stock?: number;
}

// ==================== 页面状态 ====================
const initialLoading = ref(false);
const selectedAddress = ref<Address | null>(null);
const cartItems = ref<CartItem[]>([]);

// 防抖定时器映射表（每个购物车项一个定时器）
const debounceTimers = ref<Map<string | number, any>>(new Map());

// 记录每个商品的原始数量（用于判断是否需要更新）
const originalQuantities = ref<Map<string | number, number>>(new Map());

// 删除操作的防抖定时器
const deleteDebounceTimer = ref<any>(null);

// ==================== 计算属性 ====================

// 是否全选
const isAllSelected = computed(() => {
  return cartItems.value.length > 0 && cartItems.value.every((item) => item.selected);
});

// 已选中商品数量
const selectedCount = computed(() => {
  return cartItems.value.filter((item) => item.selected).length;
});

// 总价
const totalPrice = computed(() => {
  const total = cartItems.value
    .filter((item) => item.selected)
    .reduce((sum, item) => sum + (item.sellingPrice / 100) * item.quantity, 0);
  return total.toFixed(2);
});

// ==================== API接口函数（待对接） ====================

/**
 * 获取购物车列表
 * 接口路径: /cart
 * 请求方式: GET
 * 返回数据: { code: 200, data: CartItem[], msg: string }
 */
const getCartList = async () => {
  try {
    const response = await request({
      url: '/cart',
      method: 'GET',
    });
    
    console.log('购物车列表响应:', response);
    
    if (response.code === 200) {
      // 处理返回数据，统一 productImage 字段
      cartItems.value = response.data.map((item: any) => ({
        ...item,
        productImage: item.mainImageUrl || item.productImage,
        selected: false, // 初始化选中状态
      }));
      
      // 初始化原始数量记录
      cartItems.value.forEach((item) => {
        originalQuantities.value.set(item.id, item.quantity);
      });
      
      console.log('购物车商品数量:', cartItems.value.length);
    } else {
      uni.showToast({
        title: response.msg || '获取购物车失败',
        icon: 'none',
      });
    }
  } catch (error) {
    console.error('获取购物车列表失败:', error);
    uni.showToast({
      title: '获取购物车失败',
      icon: 'none',
    });
  }
};

/**
 * 更新购物车商品数量（带防抖）
 * 接口路径: /cart/{id}?quantity={quantity}
 * 请求方式: PUT
 * 请求参数: id (路径参数), quantity (查询参数)
 */
const updateCartQuantity = (cartId: string | number, newQuantity: number) => {
  // 检查数量是否变化
  const originalQuantity = originalQuantities.value.get(cartId);
  if (originalQuantity === newQuantity) {
    console.log('数量未变化，不调用接口');
    return;
  }

  // 清除该商品之前的定时器
  const existingTimer = debounceTimers.value.get(cartId);
  if (existingTimer) {
    clearTimeout(existingTimer);
  }

  // 设置新的防抖定时器（500ms）
  const timer = setTimeout(async () => {
    try {
      console.log('调用更新数量接口:', { cartId, newQuantity });

      const response = await request({
        url: `/cart/${cartId}?quantity=${newQuantity}`,
        method: 'PUT',
      });

      if (response.code === 200) {
        // 更新成功，更新原始数量记录
        originalQuantities.value.set(cartId, newQuantity);
        console.log('更新购物车数量成功');
      } else {
        uni.showToast({
          title: response.msg || '更新数量失败',
          icon: 'none',
        });
        // 更新失败，恢复原始数量
        const item = cartItems.value.find((i) => i.id === cartId);
        if (item && originalQuantity !== undefined) {
          item.quantity = originalQuantity;
        }
      }
    } catch (error) {
      console.error('更新购物车数量失败:', error);
      uni.showToast({
        title: '更新数量失败',
        icon: 'none',
      });
      // 更新失败，恢复原始数量
      const item = cartItems.value.find((i) => i.id === cartId);
      if (item && originalQuantity !== undefined) {
        item.quantity = originalQuantity;
      }
    } finally {
      // 清除定时器
      debounceTimers.value.delete(cartId);
    }
  }, 500);

  // 保存定时器
  debounceTimers.value.set(cartId, timer);
};

/**
 * 删除购物车商品（带防抖）
 * 接口路径: /cart/{id}
 * 请求方式: DELETE
 * 请求参数: id (路径参数)
 */
const deleteCartItem = async (cartId: string | number) => {
  // 清除之前的防抖定时器
  if (deleteDebounceTimer.value) {
    clearTimeout(deleteDebounceTimer.value);
  }

  // 设置新的防抖定时器（300ms）
  deleteDebounceTimer.value = setTimeout(async () => {
    try {
      console.log('调用删除接口:', cartId);

      const response = await request({
        url: `/cart/${cartId}`,
        method: 'DELETE',
      });

      if (response.code === 200) {
        // 删除成功，刷新购物车列表
        console.log('删除成功，刷新列表');
        await getCartList();
      } else {
        uni.showToast({
          title: response.msg || '删除失败',
          icon: 'none',
        });
      }
    } catch (error) {
      console.error('删除购物车商品失败:', error);
      uni.showToast({
        title: '删除失败，请重试',
        icon: 'none',
      });
    } finally {
      deleteDebounceTimer.value = null;
    }
  }, 300);
};

/**
 * 获取默认收货地址
 * TODO: 后续对接真实接口
 * 接口路径: /api/address/default
 * 请求方式: GET
 */
const getDefaultAddress = async () => {
  try {
    // TODO: 后续替换为真实接口调用
    // const response = await request({
    //   url: '/address/default',
    //   method: 'GET',
    // });
    // if (response.code === 200 && response.data) {
    //   selectedAddress.value = response.data;
    // }

    // ========== 以下是Mock数据，后续删除 ==========
    selectedAddress.value = {
      id: 1,
      receiverName: '张三',
      receiverPhone: '138****8888',
      province: '江苏省',
      city: '南京市',
      district: '玄武区',
      address: '某某街道某某号',
      fullAddress: '江苏省南京市玄武区某某街道某某号',
      isDefault: true,
    };
    // ========== Mock数据结束 ==========
  } catch (error) {
    console.error('获取默认地址失败:', error);
  }
};

// ========== Mock数据函数已删除，使用真实接口 ==========

// ==================== 事件处理函数 ====================

/**
 * 切换商品选中状态
 */
const toggleItemSelect = (item: CartItem) => {
  item.selected = !item.selected;
};

/**
 * 全选/取消全选
 */
const toggleSelectAll = () => {
  const newSelectState = !isAllSelected.value;
  cartItems.value.forEach((item) => {
    item.selected = newSelectState;
  });
};

/**
 * 增加商品数量
 */
const increaseQuantity = (item: CartItem) => {
  if (item.stock && item.quantity >= item.stock) {
    uni.showToast({
      title: '库存不足',
      icon: 'none',
    });
    return;
  }
  
  // 先增加本地数量
  item.quantity++;
  
  // 调用防抖更新函数
  updateCartQuantity(item.id, item.quantity);
};

/**
 * 减少商品数量
 */
const decreaseQuantity = (item: CartItem) => {
  if (item.quantity <= 1) {
    uni.showToast({
      title: '数量不能少于1',
      icon: 'none',
    });
    return;
  }
  
  // 先减少本地数量
  item.quantity--;
  
  // 调用防抖更新函数
  updateCartQuantity(item.id, item.quantity);
};

/**
 * 删除商品
 */
const deleteItem = (item: CartItem) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除该商品吗？',
    success: async (res) => {
      if (res.confirm) {
        await deleteCartItem(item.id);
      }
    },
  });
};

/**
 * 跳转到商品详情
 */
const goToProductDetail = (item: CartItem) => {
  uni.navigateTo({
    url: `/pages/product/detail?id=${item.productId}`,
  });
};


/**
 * 跳转到首页
 */
const goToHome = () => {
  uni.switchTab({
    url: '/pages/index/index',
  });
};

/**
 * 立即下单（结算）
 * 接口路径: /order
 * 请求方式: POST
 * 请求参数: { orderItemList: [{ productId, productNum }] }
 */
const checkout = async () => {
  if (selectedCount.value === 0) {
    uni.showToast({
      title: '请选择商品',
      icon: 'none',
    });
    return;
  }

  // 获取选中的商品
  const selectedItems = cartItems.value.filter((item) => item.selected);

  console.log('准备下单的商品:', selectedItems);

  try {
    uni.showLoading({
      title: '正在创建订单...',
    });

    const response = await request({
      url: '/order',
      method: 'POST',
      data: {
        orderItemList: selectedItems.map((item) => ({
          productId: item.productId,
          productNum: item.quantity,
        })),
      },
    });

    console.log('创建订单响应:', response);

    uni.hideLoading();

    if (response.code === 200) {
      uni.showToast({
        title: '下单成功',
        icon: 'success',
      });

      // 跳转到订单页面
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/user/orders?fromOrderSuccess=true',
        });
      }, 1500);
    } else {
      uni.showToast({
        title: response.msg || '创建订单失败',
        icon: 'none',
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('创建订单失败:', error);
    uni.showToast({
      title: '创建订单失败，请重试',
      icon: 'none',
    });
  }
};

/**
 * 检查登录状态
 */
const checkLoginStatus = () => {
  const storedUserInfo = getUserInfo();
  if (!storedUserInfo) {
    console.log('购物车页面：用户未登录，跳转到登录页');
    uni.navigateTo({
      url: '/pages/user/login',
    });
    return false;
  }
  return true;
};

/**
 * 初始化页面数据
 */
const initPageData = async () => {
  // 暂时不加载默认地址，因为购物车页面已注释掉地址区域
  // await Promise.all([getDefaultAddress(), getCartList()]);
  await getCartList();
};

// ==================== 生命周期 ====================

onShow(async () => {
  initialLoading.value = true;

  try {
    // 检查登录状态
    if (!checkLoginStatus()) {
      await new Promise((resolve) => setTimeout(resolve, 800));
      return;
    }

    // 初始化页面数据
    await initPageData();
  } catch (error) {
    console.error('页面初始化失败:', error);
  } finally {
    initialLoading.value = false;
  }
});

onMounted(() => {
  // 组件挂载时初始化
});

// 页面卸载时清理所有定时器
onUnmounted(() => {
  // 清理数量更新的防抖定时器
  debounceTimers.value.forEach((timer) => {
    clearTimeout(timer);
  });
  debounceTimers.value.clear();
  
  // 清理删除操作的防抖定时器
  if (deleteDebounceTimer.value) {
    clearTimeout(deleteDebounceTimer.value);
    deleteDebounceTimer.value = null;
  }
});
</script>

<style scoped>
.cart-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

/* 全屏加载动画 */
.initial-loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #ffffff;
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.initial-loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.initial-loading-spinner {
  width: 70rpx;
  height: 70rpx;
  border: 6rpx solid rgba(255, 102, 0, 0.2);
  border-top: 6rpx solid #ff6600;
  border-radius: 50%;
  animation: spin 1.5s cubic-bezier(0.4, 0, 0.2, 1) infinite;
  margin-bottom: 40rpx;
}

.initial-loading-text {
  font-size: 32rpx;
  color: #ff6600;
  font-weight: 600;
  letter-spacing: 0.02em;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 收货地址 */
.address-section {
  background: #fff;
  padding: 24rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.address-icon {
  margin-right: 16rpx;
}

.address-content {
  flex: 1;
}

.address-info {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.address-header {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.receiver-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.receiver-phone {
  font-size: 28rpx;
  color: #666;
}

.address-detail {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
}

.address-empty {
  padding: 8rpx 0;
}

.address-empty-text {
  font-size: 28rpx;
  color: #999;
}

.address-arrow {
  margin-left: 16rpx;
}

/* 购物车列表滚动区域 */
.cart-list-scroll {
  flex: 1;
  overflow-y: auto;
}

/* 购物车列表 */
.cart-list {
  background: #fff;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
  position: relative;
}

.item-checkbox {
  padding: 8rpx;
  margin-right: 16rpx;
}

.checkbox {
  width: 40rpx;
  height: 40rpx;
  border: 2rpx solid #ddd;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.checkbox.checked {
  background: #ff6600;
  border-color: #ff6600;
}

.item-content {
  flex: 1;
  display: flex;
  gap: 16rpx;
}

.item-image {
  width: 180rpx;
  height: 180rpx;
  border-radius: 8rpx;
  background: #f5f5f5;
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.item-name {
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  word-break: break-word;
}

.item-spec {
  font-size: 24rpx;
  color: #999;
  margin-top: 8rpx;
}

.item-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 8rpx;
}

.item-price {
  font-size: 32rpx;
  color: #ff6600;
  font-weight: 600;
}

.item-quantity {
  display: flex;
  align-items: center;
  border: 1rpx solid #e5e5e5;
  border-radius: 8rpx;
  overflow: hidden;
}

.quantity-btn {
  width: 56rpx;
  height: 56rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  transition: all 0.3s ease;
}

.quantity-btn:active {
  background: #e5e5e5;
}

.quantity-icon {
  font-size: 32rpx;
  color: #666;
}

.quantity-num {
  min-width: 60rpx;
  height: 56rpx;
  line-height: 56rpx;
  text-align: center;
  font-size: 28rpx;
  color: #333;
}

.item-delete {
  padding: 8rpx;
  margin-left: 16rpx;
}

/* 空购物车 */
.empty-cart {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #fff;
}

.empty-icon {
  width: 160rpx;
  height: 160rpx;
  margin-bottom: 24rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 40rpx;
}

.go-shopping-btn {
  width: 240rpx;
  /* height: 80rpx;
  line-height: 80rpx; */
  background: linear-gradient(135deg, #ff6600 0%, #ff8800 100%);
  color: #fff;
  border-radius: 40rpx;
  font-size: 28rpx;
  border: none;
}

/* 底部操作栏 */
.bottom-bar {
  flex-shrink: 0;
  background: #fff;
  padding: 20rpx 24rpx;
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  z-index: 100;
}

.select-all {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-right: 24rpx;
}

.select-all-text {
  font-size: 28rpx;
  color: #333;
}

.total-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.total-info {
  display: flex;
  align-items: baseline;
}

.total-label {
  font-size: 28rpx;
  color: #666;
}

.total-price {
  font-size: 36rpx;
  color: #ff6600;
  font-weight: 600;
}

.total-tip {
  font-size: 22rpx;
  color: #999;
  margin-top: 4rpx;
}

.checkout-btn {
  width: 240rpx;
  height: 80rpx;
  line-height: 80rpx;
  background: linear-gradient(135deg, #ff6600 0%, #ff8800 100%);
  color: #fff;
  border-radius: 40rpx;
  font-size: 28rpx;
  border: none;
  margin-left: 24rpx;
}

.checkout-btn[disabled] {
  background: #ccc;
  opacity: 0.6;
}
</style>

